package com.framework.seedkit.device.nfc;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.tech.IsoDep;
import android.nfc.tech.NfcF;
import android.os.Build;
import android.os.Parcelable;
import android.provider.Settings;

import com.framework.seedkit.R;
import com.framework.seedkit.utils.LOG;
import com.framework.seedkit.utils.StringUtil;

import java.nio.charset.Charset;

/**
 * 此类是NFC辅助工具类,主要实现标签检测,前台数据分发,交易数据的获取与解析
 * 
 */
public class NFCUtil {

	private static final String TAG = NFCUtil.class.getSimpleName();

	private Activity mActivity;

	private NfcAdapter mNfcAdapter = null;

	private PendingIntent mPendingIntent = null;

	private IntentFilter mFilters[] = null;

	private final IntentFilter ndefFilter = new IntentFilter(
			NfcAdapter.ACTION_NDEF_DISCOVERED);
	private final IntentFilter techFilter = new IntentFilter(
			NfcAdapter.ACTION_TECH_DISCOVERED);
	// 过滤nfc tag
	private String mTechLists[][] = new String[][] {
			new String[] { NfcF.class.getName() },
			new String[] { IsoDep.class.getName() } };

	/**
	 * NF工具构造函数
	 */
	public NFCUtil(Activity mActivity) {
		this.mActivity = mActivity;
		initNfcForegroundDispatch();
	} 
	
	/**
	 *  初始化前台发布
	 * @param
	 * @returnType void
	 */
	private void initNfcForegroundDispatch() {
		mNfcAdapter = NfcAdapter.getDefaultAdapter(mActivity);
		mPendingIntent = PendingIntent.getActivity(mActivity, 0,// requestCode
				new Intent(mActivity, mActivity.getClass())
						.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);// flag

		try {
			ndefFilter.addDataType("text/plain");
			techFilter.addDataType("*/*");
		} catch (MalformedMimeTypeException e) {
			LOG.e(TAG,"MalformedMimeTypeException");
			throw new RuntimeException("fail", e);
		} 
		// 过滤nfc Intent
		mFilters = new IntentFilter[] { ndefFilter, techFilter }; 
	}
 
	/**
	 * 激活nfc前台推送，onResume调用
	 */
	public void enableForegroundDispatch() {
		if (isSupportNFC()) {
			mNfcAdapter.enableForegroundDispatch(mActivity, mPendingIntent,
					mFilters, mTechLists);
			LOG.d(TAG, "***************enableForegroundDispatch***************");
		}
	} 
	 
	/**
	 * 关闭nfc前台推送  ，onPause调用
	 */
	public void disableForegroundDispatch() {
		if (isSupportNFC()) {
			mNfcAdapter.disableForegroundDispatch(mActivity);
			LOG.d(TAG, "***************disableForegroundDispatch***************");
		}
	}

	/**
	 * 是否支持NFC功能
	 */
	public boolean isSupportNFC() {
		if (mNfcAdapter == null) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 发送NFC消息
	 */
	public void sendNfcMSG(String sendString) {
		if (!StringUtil.isNotEmpty(sendString)) {
			return;
		}
		NdefRecord ndefRecord = createMimeRecord("*/*", sendString.getBytes());
		NdefRecord[] ndefRecords = new NdefRecord[] { ndefRecord };
		NdefMessage ndefMessage = new NdefMessage(ndefRecords);

		if (isSupportNFC()) {
			mNfcAdapter.disableForegroundNdefPush(mActivity);
			mNfcAdapter.enableForegroundNdefPush(mActivity, ndefMessage);
		}
	}

	/**
	 * @Title: createMimeRecord
	 * @Description: 创建NFC Record
	 * @param mime
	 * @param payload
	 * @return
	 * @author scofieldandroid@gmail.com
	 * @returnType NdefRecord
	 */
	private NdefRecord createMimeRecord(String mime, byte[] payload) {
		byte[] type = mime.getBytes(Charset.forName("UTF-8"));
		NdefRecord record = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, type,
				new byte[0], payload);
		return record;
	}




	/**
	 * @Title: getNfcMSG
	 * @Description: 获取NFC传递的消息
	 * @return
	 * @author scofieldandroid@gmail.com
	 * @returnType String
	 */
	public String getNfcMSG(Intent intent) {
		String nfcMSG = null;

		if (isNFCAction(intent)) {
			try {
				Parcelable[] parcelableArray = intent
						.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

				NdefMessage ndefMessage = (NdefMessage) parcelableArray[0];
				byte[] bytes = ndefMessage.getRecords()[0].getPayload();
				nfcMSG = new String(bytes);
			}catch (Exception e) {
				e.printStackTrace();
			}

		} else {
			nfcMSG = null;
		}

		return nfcMSG;
	}

	/**
	 * @Title: validateNfcMSG
	 * @Description: 校验NFC 消息是否合法
	 * @param content
	 * @param prefixRule
	 * @return
	 * @author scofieldandroid@gmail.com
	 * @returnType boolean
	 */
	public boolean validateNfcMSG(String content, String prefixRule) {
		boolean validity = false;
		if (content != null && prefixRule != null) {
			if (content.startsWith(prefixRule)) {
				validity = true;
			}
		}
		return validity;
	}

	/**
	 * @Title: getValidateNfcMSG
	 * @Description: 获取合法的NFC消息
	 * @param intent
	 * @param prefixRule
	 * @return 返回合法的数据，如果不合法直接返回null
	 * @author scofieldandroid@gmail.com
	 * @returnType String
	 */
	public String getValidateNfcMSG(Intent intent, String prefixRule) {
		String validateNfcMSG = null;
		String nfcMSG = null;

		nfcMSG = getNfcMSG(intent);

		if (validateNfcMSG(nfcMSG, prefixRule)) {
			validateNfcMSG = nfcMSG.substring(prefixRule.length());
		} else {
			validateNfcMSG = null;
		}

		return validateNfcMSG;
	}

	/**
	 * @Title: isNFCAction
	 * @Description: 判断当前的intent Action是否为NFC Action
	 * @param intent
	 * @return
	 * @author scofieldandroid@gmail.com
	 * @returnType boolean
	 */
	public boolean isNFCAction(Intent intent) {

		return NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction());
	}

	/**
	 * @Title: updateNfcMSG
	 * @Description: 更新NFC消息,返回校验后的数据
	 * @param intent
	 * @author scofieldandroid@gmail.com
	 * @returnType String
	 */
	public String updateNfcMSG(Intent intent) {
		String NFC_MSG_PREFIXRULE = "SEED_NFC";
		String validateNfcMSG = getValidateNfcMSG(intent,
				NFC_MSG_PREFIXRULE);
		//此处可以根据业务需要,将获取到的NFC消息保存起来并传递到UI主线程中
		//用于页面的数据刷新

		return validateNfcMSG;
	}

	/**
	 * @Title: parseNfcMsgToLinkedAccount
	 * @Description: 解析NFC-->LinkedAccount
	 * @param nfcString
	 * @return
	 * @author scofieldandroid@gmail.com
	 * @returnType LinkedAccount
	 */
	public LinkedAccount parseNfcMsgToLinkedAccount(String nfcString) {
		LinkedAccount linkedAccountRemote = null;
		try {
			linkedAccountRemote = new LinkedAccount();
			String[] array = nfcString.split("\\|");
			linkedAccountRemote.setMoneyType(array[0]);// 0-交易币种
			linkedAccountRemote.setTransferMoney(array[1]);// 1-收款金额
			linkedAccountRemote.setTransferMoneyUppercase(array[2]);// 2-大写金额
			linkedAccountRemote.setUse(array[3]);// 3-收款事由
			linkedAccountRemote.setGatheringAccount(array[4]);// 4-接受人看到的 收款账号
			linkedAccountRemote.setGatheringAccountName(array[5]);// 5-接受人看到的
																	// 收款人名称

		} catch (Exception e) {
		}
		return linkedAccountRemote;
	}

	/**
	 * @Title: getPbocNFCState
	 * @Description:判断是否开启NFC
	 * @param con
	 * @author Jiawei.Li
	 */
	public static void getPbocNFCState(final Activity con) {
		NfcAdapter adapter = NfcAdapter.getDefaultAdapter(con);
		if (adapter != null) {
			if (!adapter.isEnabled()) {

				new AlertDialog.Builder(con.getParent())
						.setMessage(R.string.iccard_nfc_no_set)
						.setPositiveButton(R.string.iccard_set_positive,
								new OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
											Intent intent = new Intent(Settings.ACTION_NFC_SETTINGS);
											con.startActivity(intent);
										} else {
											Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
											con.startActivity(intent);
										}
									}
								})
						.setNegativeButton(R.string.iccard_set_negative,
								new OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										con.finish();
									}
								}).create().show();

			}
		} else {

			new AlertDialog.Builder(con.getParent())
					.setMessage(R.string.iccard_nfc_no)
					.setPositiveButton(R.string.iccard_set_positive,
							new OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									con.finish();
								}
							}).create().show();
		}

	}
}
